package com.sky.loveshop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.sky.loveshop.entity.MqttClientTopicRelation;
import com.sky.loveshop.entity.MqttTopic;
import com.sky.loveshop.mapper.MqttClientTopicRelationMapper;
import com.sky.loveshop.mapper.MqttTopicMapper;
import com.sky.loveshop.service.MqttTopicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/11/17 20:52
 */
@Slf4j
@Service
public class MyMqttTopicServiceImpl implements MqttTopicService {

    @Resource
    private MqttTopicMapper mqttTopicMapper;
    @Resource
    private MqttClientTopicRelationMapper relationMapper;
    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Override
    public List<MqttTopic> listAll() {
        return mqttTopicMapper.selectAll();
    }

    @Override
    public List<MqttTopic> listAllByEnv() {
        Example example = new Example(MqttTopic.class);
        example.createCriteria().andEqualTo("env", activeProfile);
        return mqttTopicMapper.selectByExample(example);
    }

    @Override
    public List<MqttTopic> getTopicsByClientId(Integer id) {
        Example example = new Example(MqttClientTopicRelation.class);
        example.createCriteria().andEqualTo("clientId", id);
        List<MqttClientTopicRelation> relationList = relationMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(relationList)) {
            return new ArrayList<>();
        }
        List<Integer> topicIdList = relationList.stream().map(MqttClientTopicRelation::getTopicId).collect(Collectors.toList());

        Example example1 = new Example(MqttTopic.class);
        example1.createCriteria().andIn("id", topicIdList);
        return mqttTopicMapper.selectByExample(example1);
    }

    @Override
    public String getTopicPathByShopIdAndType(Integer shopId, Integer commandType) {
        Example example = new Example(MqttTopic.class);
        example.createCriteria()
                .andEqualTo("shopId", shopId)
                .andEqualTo("commandType", commandType)
                .andEqualTo("env", activeProfile);
        MqttTopic mqttTopic = mqttTopicMapper.selectOneByExample(example);
        return mqttTopic.getTopicPath();
    }
}
